#include "Collision.h"
#include "Config.h"
#include "HelloWorldScene.h"
#include "Branch.h"
#include "cocos2d.h"

USING_NS_CC;

/****************************************************
* Name			: Constructor
* Param			: Branch * br
* Mission		: Constructor for Collision class
* Modify date	: 15/5/2014
* Author		: Phuoctd
****************************************************/
Collision::Collision(Monkey * monkey )
{
	setName("Collision");
	this->mMonkey = monkey;
	mSizeScreen = CCDirector::sharedDirector()->getWinSize();
}


/****************************************************
* Name			: Update
* Param			: float delta_time
* Mission		: Update collision between Branch and Monkey
* Modify date	: 15/5/2014
* Author		: Phuoctd
****************************************************/
void Collision::update(float ct)
{
	if(mMonkey->fGet_mIsDie() == 1)
	{
		return;
	}
	mParent = (Branch * ) getOwner();
	if(mParent== NULL )
	{
		return;
	}

	if(mParent->mIsPointed == 0)
	{
		if(mParent->getPositionY() > mMonkey->getPositionY() + mMonkey->boundingBox().size.height*3/4)
		{
			mParent->mIsPointed = 1;
			mMonkey->fSetScore(mMonkey->fGetScore() + 1);
			mMonkey->fUpdateScore();
		}		
	}

	if(isCollision())
	{
		mMonkey->fMonkeyDie();
	}
}

/****************************************************
* Name			:
* Param			:
* Mission		:
* Modify date	: 
* Author		: Phuoctd
****************************************************/
int Collision::isCollision()
{
	CCSize monkey_size = mParent->boundingBox().size;
    CCPoint monkey_position = getWorldPosition();
    
    CCSize branch_size = mMonkey->boundingBox().size;
    CCPoint branch_position = mMonkey->getPosition();
    
    float d = 15; //gia giam de chim dung vao pipe nhieu hon....
    
    float maxx1 = branch_position.x + branch_size.width/2 - d;
    float minx1 = branch_position.x - branch_size.width/2 + d;
    float maxy1 = branch_position.y + branch_size.height/2 - d;
    float miny1 = branch_position.y - branch_size.height/2 + d;
    
    float maxx2 = monkey_position.x + monkey_size.width/2 - d;
    float minx2 = monkey_position.x - monkey_size.width/2 + d;
    float maxy2 = monkey_position.y + monkey_size.height/2 - d;
    float miny2 = monkey_position.y - monkey_size.height/2 + d;
    
    return !(maxx1 < minx2 ||
             maxx2 < minx1 ||
             maxy1 < miny2 ||
             maxy2 < miny1);
}

/****************************************************
* Name			:
* Param			:
* Mission		:
* Modify date	: 
* Author		: Phuoctd
****************************************************/
CCPoint Collision::getWorldPosition()
{
    return ((CCParallaxNode*)mParent->getParent())->convertToWorldSpace(mParent->getPosition());
}